package dsl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import dsl.common.domain.EventList;
import dsl.common.domain.VariableList;
import dsl.common.exception.GrammarIsWrongException;
import dsl.module.parser.Parser;
import dsl.module.responder.Responder;
import dsl.utils.GUI;
import dsl.utils.MyLogger;

public class Application {
    /**
     * 通过{@link dsl.utils.GUI}以对话框方式告知用户语法错误与取得脚本文件
     * 先通过语法分析器{@link dsl.module.parser.Parser}取得事件列表与变量列表
     * 等待客户端的接入，当客户接入时，创建一个应答进程{@link dsl.module.responder.Responder}与客户端对话
     * 
     * @param args
     */
    public static void main(String[] args) {
        // 先通过语法分析器取得事件列表与变量列表
        Parser parser = new Parser();
        String inFilePath = GUI.getInFilePath();
        EventList events = null;
        VariableList variables = null;
        try {
            MyLogger.logger.info("start the analysis program");
            int res = parser.readProgram(inFilePath);
            if (res == Parser.FILE_NOT_FOUND) {
                MyLogger.logger.warning("FILE NOT FOUND");
                GUI.showInfo("InputFilePath is wrong!");
                return;
            } else if (res == Parser.IO_ERROR) {
                GUI.showInfo("Sorry! IO error in analysis program!");
                return;
            }
            events = parser.getEvents();
            variables = parser.getVariables();
            MyLogger.logger.info("analysis program end");
        } catch (GrammarIsWrongException e) {
            MyLogger.logger.warning("PROGRAM IS WRONG");
            GUI.showInfo(e.getMessage() + "!");
        }

        // 等待客户端的接入，当客户接入时，创建一个应答进程与客户端对话
        // 默认服务器端口号为8000
        int port = 8000;
        ServerSocket server;
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        try {
            server = new ServerSocket(port);
            MyLogger.logger.info("create seversocket");
            while (true) {
                Socket client = server.accept();
                MyLogger.logger.info("connect with client");
                Responder robot = new Responder(client, events, variables);
                threadPool.submit(robot);
            }
        } catch (IOException e) {
            MyLogger.logger.warning("FAIL TO CREATE SERVERSOCKET");
            GUI.showInfo("Sorry! fail to create server!");
        }
    }
}
